package silencify;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;

public class Silencify extends Thread {
	private static BufferedImage searchImage;
	private static TrayItem trayItem;
	private static Image okImage;
	private static Image notOkImage;
	private static Image lostContactImage;
	private static Display display = new Display();
	private static final Shell shell = new Shell(display);

	private static final int dax = -53;
	private static final int day = 18;
	private static final int dbx = -42;
	private static final int dby = 18;
	private static final int dclickx = 0;
	private static final int dclicky = 18;
	private static final Silencify silencify = new Silencify();
	
	private Robot robot = null;
	private int[] a = new int[2];
	private int[] b = new int[2];
	private int[] click = new int[2];
	private static final Color BCOLOR = new Color(87,87,87);
	private static final Color WHITE = new Color(254,254,254);
	private boolean requestSearch = true;
	private boolean muted = false;
	private static final int AUTODELAY = 70;
	private enum State {
		LOSTCONTACT(3000),
		OK(1000),
		ALERTOK(100),
		NOTOK(300);
		private int ms;

		State(int ms) {
			this.ms = ms;
		}
		
	};
	private static Image getImage(State state) {
		switch (state) {
		case OK: return okImage;
		case ALERTOK: return okImage;
		case NOTOK: return notOkImage;
		case LOSTCONTACT: return lostContactImage;
		}
		return null;
	}
	private State state = State.LOSTCONTACT;
	
	@Override
	public void run() {
		while (!shell.isDisposed()) {
			try {
				if (robot == null || requestSearch) {
					if (searchHotSpot()) {
						state = getCompanionState();
						setTrayState(state);
					}
					synchronized (this) {
						requestSearch = false;
					}
				} else {
					State newState = getCompanionState();
					adjust(newState);
					setTrayState(state);
				}
				Thread.sleep(state.ms);
			} catch (InterruptedException e) {
				break;
			}
		}
	}
	private State getCompanionState() {
		Color ca = robot.getPixelColor(a[0], a[1]);
		Color cb = robot.getPixelColor(b[0], b[1]);
		//System.out.printf("color a:%s%n", ca);

		if (cb.equals(BCOLOR)) {
			return ca.equals(BCOLOR) ? State.NOTOK : ca.equals(WHITE) ? State.ALERTOK : State.OK;
		} else {
			return State.LOSTCONTACT;
		}
	}
	private void mouseMove(int[] pos) {
		robot.mouseMove(pos[0], pos[1]);
	}

	private boolean searchHotSpot() {
		try {
			Pair<Point, Robot> p = ScreenScraper.findRegion(searchImage);
			if (p != null) {
				robot = p.b;
				robot.setAutoDelay(AUTODELAY);
				a[0] = p.a.x + dax;
				a[1] = p.a.y + day;
				b[0] = p.a.x + dbx;
				b[1] = p.a.y + dby;
				click[0] = p.a.x + dclickx;
				click[1] = p.a.y + dclicky;
				return true;
			} else {
				return false;
			}
		} catch (AWTException e) {
		}
		return false;
	}

	private void adjust(State newState) {
		if (newState == state) return;
		System.out.printf("%s->%s%n",state, newState);
		switch (newState) {
		case NOTOK: 
			mute(true);
//			if (System.currentTimeMillis() % 20 == 17) play();
			break;
		case OK: 
		case ALERTOK: 
		case LOSTCONTACT: 
			mute(false); 
			break;
		}
		state = newState;
	}
	
//	private static void xplay() {
//		new Thread() {
//			@Override
//			public void run() {
//				InputStream is = Silencify.class.getResourceAsStream("/silencify.mp3");
//				JLayerPlayer.playMp3(is);
//			}
//		}.start();
//	}
	private void mute(boolean m) {
		if (muted == m) return;
		robot.setAutoDelay(0);
		mouseMove(click);
		robot.mousePress(InputEvent.BUTTON1_MASK);
		robot.mouseRelease(InputEvent.BUTTON1_MASK);
		robot.setAutoDelay(AUTODELAY);
		keyType(KeyEvent.VK_CONTROL, KeyEvent.VK_SHIFT, KeyEvent.VK_DOWN);
		if (m) {
			keyType(KeyEvent.VK_SPACE);
		} else {
//			keyType(KeyEvent.VK_SPACE);
//			keyType(KeyEvent.VK_SPACE);
//			if (hasPlayed) {
//				System.out.printf("hasPlayed%n");
//				keyType(KeyEvent.VK_SPACE);
//				keyType(KeyEvent.VK_SPACE);
//				hasPlayed = false;
//			}
		}
		keyType(KeyEvent.VK_ALT, KeyEvent.VK_TAB);
		muted = m;
	}
	private void keyType(int... codes) {
		for (int i=0 ; i<codes.length ; i++)
			robot.keyPress(codes[i]);
		for (int i=codes.length-1 ; i>=0 ; i--)
			robot.keyRelease(codes[i]);
	}

	/**
	 * @param args
	 * @throws IOException 
	 * @throws AWTException
	 * @throws IOException
	 * @throws InterruptedException 
	 */
	// public static void main(String[] args) throws IOException, AWTException {
	// Silencify s = new Silencify();
	//
	// }
	
	public static void main(String[] args) throws IOException, InterruptedException {
		searchImage = ImageIO.read(Silencify.class.getResourceAsStream("/spotify-region.png"));
		

		ImageLoader loader = new ImageLoader();
		ImageData[] tab1 = loader.load(Silencify.class.getResourceAsStream("/ok.png"));
		okImage = new Image(display, tab1[0]);
		tab1 = loader.load(Silencify.class.getResourceAsStream("/not-ok.png"));
		notOkImage = new Image(display, tab1[0]);
		tab1 = loader.load(Silencify.class.getResourceAsStream("/lost-contact.png"));
		lostContactImage = new Image(display, tab1[0]);
		final Tray tray = display.getSystemTray();
		if (tray == null) {
			System.out.println("The system tray is not available");
		} else {
			final TrayItem item = new TrayItem(tray, SWT.NONE);
			trayItem = item;
			item.setToolTipText("Silencify");
			final Menu menu = new Menu(shell, SWT.POP_UP);
			MenuItem mi = new MenuItem(menu, SWT.PUSH);
			mi.setText("Search");
			mi.addListener(SWT.Selection, new Listener() {
				public void handleEvent(Event event) {
					synchronized (this) {
						silencify.requestSearch = true;
					}
				}
			});
			mi = new MenuItem(menu, SWT.PUSH);
			mi.setText("Exit");
			mi.addListener(SWT.Selection, new Listener() {
				public void handleEvent(Event event) {
					shell.dispose();
				}
			});
			mi = new MenuItem(menu, SWT.PUSH);
			mi.setText("Test");
			mi.addListener(SWT.Selection, new Listener() {
				public void handleEvent(Event event) {
					silencify.mouseMove(silencify.a);
				}
			});
			item.addListener(SWT.MenuDetect, new Listener() {
				public void handleEvent(Event event) {
					menu.setVisible(true);
				}
			});
			item.setImage(lostContactImage);
		}
		shell.setBounds(50, 50, 100, 100);
		shell.setActive();

		silencify.start();
//		Thread.sleep(1000);
//		silencify.adjust();
		
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		okImage.dispose();
		notOkImage.dispose();
		lostContactImage.dispose();
		display.dispose();
	}



	private static void setTrayState(final State state) {
		if (!display.isDisposed())
			display.asyncExec(new Runnable() {
				public void run() {
					trayItem.setImage(getImage(state));
				}
			});
	}
}
